import CryptoJS from '@/node_modules/crypto-js/crypto-js.js'
// 引入Vuex状态管理
import store from '@/store/index.js';
// import {config} from '@/config/config1.js';
import {config} from '@/config/config.js'; 
//#ifdef  H5
	let jweixin = require('jweixin-module')
//#endif

const GetApi = function(opt){
	
	let desBusinessCode = encryptDes(config.business_code)
	
    opt = opt || {};
    opt.url = config.api_url+opt.url || '';
    opt.data = opt.data || '';
    opt.method = opt.method || 'Post';
    opt.header = opt.header || {
        "Content-Type": "application/json",
		"Authorization":store.getters.token,
		"Business-Code":desBusinessCode,
		// "Isbuyer":store.getters.isbuyer||0
    };
	
    opt.success = opt.success || function () {};
// console.log(store.getters.isbuyer,'isbuyer*****')
    uni.request({
        url:opt.url,
        data: opt.data,
        method: opt.method,
        header: opt.header,
        dataType: 'json',
        success: function (res) {
					//console.log(res)
			if(res.data.status==0 && res.data.code==1001){
				//清除token
				store.dispatch('setToken','')
				//console.log(res.data.token)
				store.dispatch('changeLogin',false)
				//清除登录状态
				//弹窗跳转到登录界面
				uni.showToast({
					icon:'none',
					title:'登录状态已过期，请重新登录'
					
				});
				
				wx.switchTab({
					url:'/pages/home/home',
					success: (res) => {
								let page = getCurrentPages().pop();
								if (page == undefined || page == null) return;
								page.curSegment = 0;
								page.onLoad();
							},
				})
			
					
				
			}else if(res.data.status==0 && res.data.code==3001){
				//微信公众号   跳转授权页
				
				let state = decryptDes(res.data.state)
				//console.log(state)
				const url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx4f84d4f38674bb53&redirect_uri=https%3A%2F%2Fwww.aiouning.com%2Fwechat%2Fh5%2FredirectRri&response_type=code&scope=snsapi_userinfo&state='+state+'#wechat_redirect'	
				window.location.href=url
				return false;
			}
			else{
				//console.log(666666)
				opt.success(res.data);
			}
			
            
        },
        fail: function () {
            uni.showToast({
                title: '网络错误，请稍后重试'
            });
        }
    })
}

const loginGetUser = function(abc){
	let _this=this;
	var opt={
		url:'/api/userinfo/base',
		success:function(res){	
		  //把个用户信息放入本地缓存
		  if(res.status==1){
			 // console.log(res);
			  uni.setStorageSync('userInfo',res.data);
				//uni.setStorageSync('hasLogin',true)
				//console.log('存入用户数据');
				abc();
		  }
		}
	};
	_this.GetApi(opt);
	
}
/*
*  DES加密 iv 
*  @msg  string  加密内容 
 * @key  string  密钥
*/
const encryptDesIv = function (msg){
	//console.log(msg)
	   const keyHex = CryptoJS.enc.Utf8.parse(config.DES_KEY);   
	   const ivHex = CryptoJS.enc.Utf8.parse(config.IV);
	   const encrypted = CryptoJS.DES.encrypt(msg, keyHex, {
		iv:ivHex,
	   mode: CryptoJS.mode.CBC,
	   padding: CryptoJS.pad.Pkcs7
	   });
	  return encrypted.toString();
}
/*
*  DES加密
*  @msg  string  加密内容 
 * @key  string  密钥
*/
const encryptDes = function (msg){
	//console.log(msg)
	   const keyHex = CryptoJS.enc.Utf8.parse(config.DES_KEY);
	   const encrypted = CryptoJS.DES.encrypt(msg, keyHex, {
	   mode: CryptoJS.mode.ECB,
	   padding: CryptoJS.pad.Pkcs7
	   });
	  return encrypted.toString();
}

/*
*  DES解密
*  @msg  string  解密内容 
 * @key  string  密钥
*/

 const decryptDes = function (msg){
	   const keyHex = CryptoJS.enc.Utf8.parse(config.DES_KEY);
	     // direct decrypt ciphertext
	     const decrypted = CryptoJS.DES.decrypt({
	        ciphertext: CryptoJS.enc.Base64.parse(msg)
	      }, keyHex, {
	        mode: CryptoJS.mode.ECB,
	        padding: CryptoJS.pad.Pkcs7
	     });
	     return decrypted.toString(CryptoJS.enc.Utf8);

}
/*
*  获取PHP设置的cookie
*  @name  string  cookie的键值 
*/
const getCookie =function (name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';'); //把cookie分割成组
	for(var i=0;i < ca.length;i++) {
	var c = ca[i]; //取得字符串
	while (c.charAt(0)==' ') { //判断一下字符串有没有前导空格
	c = c.substring(1,c.length); //有的话，从第二位开始取
	}
	if (c.indexOf(nameEQ) == 0) { //如果含有我们要的name
	return unescape(c.substring(nameEQ.length,c.length)); //解码并截取我们要值
	}
	}
	return false;
}
/*
*  加载初始公众号配置
*  @retrun  void 
*/
const initWxH5Config = ()=> {
		var opt={
			url:'wechat/index/getWxH5Config',
			success:function(res){
				//console.log(res)
				let desString = JSON.parse(decryptDes(res.data.desString))
			
				//微信公众号
				if(res.status>0)
				{
						jweixin.config({
						  debug: desString.debug, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
						  appId: desString.appId, // 必填，公众号的唯一标识
						  timestamp: desString.timestamp, // 必填，生成签名的时间戳
						  nonceStr: desString.nonceStr, // 必填，生成签名的随机串
						  signature: desString.signature,// 必填，签名
						  jsApiList: desString.jsApiList// 必填，需要使用的JS接口列表
						});	
					//console.log(99)
					// jweixin.error(function(res){
					//   // config信息验证失败会执行error函数，如签名过期导致验证失败，具体错误信息可以打开config的debug模式查看，也可以在返回的res参数中查看，对于SPA可以在这里更新签名。
					// 	console.log(res)
					// });
				
				}
			
				
			}	
		};
		//console.log(99999)						
		GetApi(opt)
}
/*解析url参数
@param field  字段
@param url   整个url
@return string|bool
*/
const getQueryVariable =function(field,url){
	var vars = url.split("param/?");
	// vars[1] = vars[1].replace(/%3D/g, "=").replace(/%26/g, "&")
	//console.log(vars)
	var param = vars[1].split("&");
	for (var i = 0; i < param.length; i++) {
		var pair = param[i].split("=");
		//console.log(pair)
		if (pair[0] == field) {
			return pair[1];
		}
	}
	return (false);
}
const getImgHost =function () {
	return config.img_host;
}	
const getQrImgHost =function () {
	return config.qr_img_host;
}
const getWssHost =function () {
	return config.wss_host;
}
const getChatWssHost =function () {
 return config.chat_host;
}

/**
   * 获取字节高4位
   * @param {data}  十六进制 0x01|十进制
   * @return {int}  高位十进制
   */
const getHeight4 = function(data){//获取高四位
    let height
    height = ((data & 0xf0) >> 4)
    return height
}
/**
   * 获取字节低4位
   * @param {data}  十六进制 0x01|十进制
   * @return {int}  低位十进制
   */
const getLow4 = function(data){//获取低四位
    let low;
    low = (data & 0x0f);
    return low;
}

/**
   * 十六进制字符串转数组
   * 1185759ac35a91143f97037002b1a266 转换 ["11", "85", "75", "9a", "c3", "5a", "91", "14", "3f", "97", "03", "70", "02", "b1", "a2", "66"]
   * @param {String} str 十六进制字符串
   */
const Str2Arr= function(str) {
    var pos = 0;
    var len = str.length;
    if (len % 2 != 0) {
      return null;
    }
    len /= 2;
    var hexA = new Array();
    for (var i = 0; i < len; i++) {
      var s = str.substr(pos, 2);
      hexA.push(s);
      pos += 2;
    }
    return hexA;
  }
  
/**
   * 十六进制数组进行异或
   * @param {Array} buffer 十六进制数组
   */
const  BytesDes= function(buffer) {
	let b = new Uint8Array(buffer)
    var des = b[0]
    for (var i = 1; i < b.length; i++) {
		// console.log(b[i])
		// console.log(i)
      des ^= b[i]
    }
    return des
  } 
/**
   * 十进制转标准十六进制 0x01 
   * 15 转 0F
   * @param {Number} num 十进制数字
   * @return 0x15 标准16进制
   */
const inttoHex= function(num) {
	// return parseInt(("0" + (Number(num).toString(16))).slice(-2).toUpperCase(), 16)
	//转
	// return ("0" + (Number(num).toString(16))).slice(-2).toUpperCase()
    return "0x"+("0" + (Number(num).toString(16))).slice(-2).toUpperCase()
  }
  
  /**
     * 十进制转标准十六进制 01 
     * 15 转 0F
     * @param {Number} num 十进制数字
     * @return 15    16进制字符串
     */
  const inttoHexStr= function(num) {
      return ("0" + (Number(num).toString(16))).slice(-2).toUpperCase()
    }
  /**
     * 获取buffer协议头
     * 15 转 0F
     * @param {Number} buffer 十进制字节数组
  	* * @param {key} key  第N个字节
     */
    const getHeadHex= function(buffer,start=0,end=1) {
      let b = new Uint8Array(buffer)
	  let headHex = '';
	  // console.log(b)
	  // console.log()
	  for(let i=start;i<end;i++){
		  if(i==0)
		  {
			headHex+='0x'+this.inttoHexStr(b[i]);			
		  }else{
			headHex+=this.inttoHexStr(b[i])  
		  }
		  
	  }
  	 return headHex;
    } 
 /**
    * buffer转十六进制
    * 15 转 0F
    * @param {Number} buffer 十进制字节数组
	* * @param {key} key  第N个字节
    */
   const buffertoHex= function(buffer,key=0) {
     let b = new Uint8Array(buffer)
	 return this.inttoHex(b[key])
   } 
  /**
     * 二进制转十六进制
     * 00001001 转 09
     * @param {String} str 二进制字符串
     */
const binTohex= function(str) {
      let hex_array = [{ key: 0, val: "0000" }, { key: 1, val: "0001" }, { key: 2, val: "0010" }, { key: 3, val: "0011" }, { key: 4, val: "0100" }, { key: 5, val: "0101" }, { key: 6, val: "0110" }, { key: 7, val: "0111" },
      { key: 8, val: "1000" }, { key: 9, val: "1001" }, { key: 'a', val: "1010" }, { key: 'b', val: "1011" }, { key: 'c', val: "1100" }, { key: 'd', val: "1101" }, { key: 'e', val: "1110" }, { key: 'f', val: "1111" }]
      let value = ''
      let list = []
      if (str.length % 4 !== 0) {
        let a = "0000"
        let b = a.substring(0, 4 - str.length % 4)
        str = b.concat(str)
      }
      while (str.length > 4) {
        list.push(str.substring(0, 4))
        str = str.substring(4);
      }
      list.push(str)
      for (let i = 0; i < list.length; i++) {
        for (let j = 0; j < hex_array.length; j++) {
          if (list[i] == hex_array[j].val) {
            value = value.concat(hex_array[j].key)
            break
          }
        }
      }
      return value
    }
export default {
	GetApi,
	loginGetUser,
	getCookie,
	decryptDes,
	encryptDes,
	initWxH5Config,
	getImgHost,
	encryptDesIv,
	getQrImgHost,
	getQueryVariable,
	getWssHost,
	getChatWssHost,
	getHeight4,
	getLow4,
	Str2Arr,
	BytesDes,
	inttoHex,
	binTohex,
	buffertoHex,
	getHeadHex,
	inttoHexStr
}
